﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ThreadLock.ViewModels;

[ObservableObject]
public partial class MainPageViewModel {
    [ObservableProperty] private int _numberUrlDownloaded;

    private List<string> _urls =
        Enumerable.Range(0, 10000).Select(p => p.ToString()).ToList();

    [RelayCommand]
    private void Download() {
        var threads = Enumerable.Range(0, 10).Select(p => new Thread(() => {
            var random = new Random();
            while (true) {
                lock (_lock) {
                    var url = _urls.FirstOrDefault();
                    if (string.IsNullOrWhiteSpace(url)) {
                        return;
                    }

                    _urls.Remove(url);
                }

                // Download url
                Thread.Sleep(random.Next(5));

                lock (_lock) {
                    NumberUrlDownloaded++;
                }
            }
        })).ToArray();
        foreach (var thread in threads) {
            thread.Start();
        }
    }

    private volatile object _lock = new object();
}